#import urllib
import json
import webapp2
import cgi
from google.appengine.api import users
from google.appengine.ext import ndb


class Level(ndb.Model):
    last_editor = ndb.UserProperty()
    last_changes = ndb.DateTimeProperty(auto_now_add=True)
    json = ndb.StringProperty(indexed=False)


class LevelLoader(webapp2.RequestHandler):
    def get(self):
        level = Level.get_by_id(self.request.get('name'))

        if level is None:
            obj = None
        else:
            obj = {
                'name': level.key.id(),
                'last_editor': level.last_editor.email(),
                'last_changes': level.last_changes.strftime("%Y-%m-%d %H:%M:%S"),
                'json': level.json
            }

        self.response.headers['Content-Type'] = 'application/json'
        self.response.out.write(json.dumps(obj))


class LevelSaver(webapp2.RequestHandler):
    def post(self):
        data = json.loads(cgi.escape(self.request.body))
        level_name = data.get('name')
        if not level_name:
            raise Exception("name is null")
        level = Level(id=level_name)
        level.last_editor = users.get_current_user()
        level.json = data.get('json')
        level.put()
        self.response.out.write(json.dumps({'name': level_name}))

application = webapp2.WSGIApplication([
                                          ('/services/GetLevel', LevelLoader),
                                          ('/services/SaveLevel', LevelSaver),
                                      ], debug=True)